import { sys } from "cc";
import { DEV } from "cc/env";
import MsgHints from "../utils/MsgHints";

const wx = window["wx"]
export default class WXTTUtils {
    static bannerAd: any = null;
    static videoAd: any = null;
    static interstitialAd: any = null;
    static gridAd: any = null
    //格子广告是否加载成功
    static gridAdLoaded: boolean = true;


    static BANNER_ID: string = "adunit-fa7b08ac6d8cf200"
    static VIDEO_ID: string = "adunit-29b5f0955ee77f59"
    static CHAPIN_ID: string = "adunit-a3615ebe31eba64a"
    static GRID_ID: string = "adunit-d4f43001efd879de"


    public static share(callback = null, shareScreen: boolean = false) {
        if (DEV || sys.isBrowser) {
            callback(true)
            return
        }


        wx.shareAppMessage({
            title: '消方块3D,真好玩',
            imageUrl: !shareScreen ? 'icon.png' : '',
            success: () => {
                if (callback) {
                    //  callback()
                }
            },
            fail: () => {

            }
        })

        WXTTUtils.onShowGame(callback)

    }
    static shareStartTimeSecond: number = 0
    static msgs = ['分享失败:需要分享到不同的群!', '分享失败:请再尝试一下哦!', , '分享失败:请不要一直打扰一个群!']
    /**
* 此方法每次点击分享就执行一次
* @param _callback处理分享的回调
*/
    public static onShowGame(_callback: any): void {
        console.log("---游戏回到前台---------------");
        // 记录点击分享的时间（秒级）
        WXTTUtils.shareStartTimeSecond = performance.now();
        let func: Function = (_res: any) => {
            let isShareSuccess: boolean = false;
            if (WXTTUtils.shareStartTimeSecond <= 0) {
                // 不处理
            } else {
                // 判断转发成功与否，按时间处理
                let interval: number = performance.now() - WXTTUtils.shareStartTimeSecond;
                WXTTUtils.shareStartTimeSecond = -1;
                // 我这里间隔设置为2.5s
                if (interval >= 3000) {
                    isShareSuccess = true;
                } else {
                    let rnd = Math.floor(Math.random() * WXTTUtils.msgs.length)
                    MsgHints.show(WXTTUtils.msgs[rnd])
                }
            }
            _callback(isShareSuccess);
            // 取消监听小游戏回到前台的事件
            window['wx'].offShow(func);
        };
        // 监听小游戏回到前台的事件
        window['wx'].onShow(func);
    }


    static onShow(callback) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            wx.onShow(function () {
                if (callback) {
                    callback();
                }
            })
        }
    }
    static showShareMenu(): void {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            wx.showShareMenu({
                menus: ['shareAppMessage', 'shareTimeline'],
                withShareTicket: true
            })
            wx.onShareAppMessage(function () {
                return {
                    title: '经典方块消除，快来一起进入神秘的世界！',
                    imageUrl: 'icon.png'
                }
            })
        }
    }
    static jump(appid): void {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            wx.navigateToMiniProgram({
                appId: appid,
                path: '',
                extraData: null,
                envVersion: 'release',
                success(res) {
                    console.log('跳转成功');
                }
            })
        }
    }
    static showTip(value: string) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            wx.showToast({ title: value, icon: 'none', duration: 1500 })
        }
    }
    static destroyBanner(): void {
        if (WXTTUtils.bannerAd != null) {
            WXTTUtils.bannerAd.destroy()
            WXTTUtils.bannerAd = null;
        }
    }

    static showBanner(): void {
        if (sys.platform == sys.Platform.WECHAT_GAME) {

            var isIPX = false;
            wx.getSystemInfo({
                success: function (res) {
                    if (res.model.search('iPhone X') != -1) {
                        isIPX = true

                    }
                }
            })
            let offsetY = 0;
            if (isIPX) {
                offsetY = -30
                //  return
            }


            let winSize = wx.getSystemInfoSync();
            let bannerHeight = 80;
            let bannerWidth = 300;
            let bannerAd = wx.createBannerAd({
                adUnitId: WXTTUtils.BANNER_ID, adIntervals: 30,
                style: {
                    left: (winSize.windowWidth - bannerWidth) >> 1,
                    top: winSize.windowHeight - bannerHeight + offsetY,
                    width: bannerWidth
                }
            })
            WXTTUtils.bannerAd = bannerAd;
            WXTTUtils.bannerAd.show();
            //微信缩放后得到banner的真实高度，从新设置banner的top 属性
            bannerAd.onResize(res => {
                bannerAd.style.top = winSize.windowHeight - bannerAd.style.realHeight + offsetY;
            })

            bannerAd.onError(err => {
                // 进行适当的提示
                console.log("banner显示", err);
            })
        }
    }
    static initInterstitialAd() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {

            if (wx.createInterstitialAd) {
                WXTTUtils.interstitialAd = wx.createInterstitialAd({ adUnitId: WXTTUtils.CHAPIN_ID })
                WXTTUtils.interstitialAd.onLoad(() => {
                    console.log('插屏初始化成功')
                    WXTTUtils.showInterstitialAd()
                })
                WXTTUtils.interstitialAd.onError((err) => {
                    console.log('interstitialAd onError event emit', err)
                })
                WXTTUtils.interstitialAd.onClose((res) => {
                    console.log('interstitialAd onClose event emit', res)
                })

            }
        }
    }
    static showInterstitialAd() {
        if (WXTTUtils.interstitialAd) {
            console.log('显示插屏广告')
            WXTTUtils.interstitialAd.show().catch((err) => {
                console.error("插屏显示错误", err)
            })
        }

    }
    static initGridAd() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            let winSize = wx.getSystemInfoSync();
            if (wx.createGridAd) {
                let gridAd = wx.createGridAd({
                    adUnitId: WXTTUtils.GRID_ID,
                    gridCount: 5,
                    style: {
                        left: (winSize.windowWidth - 300) * 0.5,
                        top: winSize.windowHeight - 80,
                        width: 300,
                        opacity: 0.9
                    }
                })
                gridAd.onError((err) => {
                    console.log('格子广告初始化错误', err);
                    if (err['errCode'] >= 1000 && err['errCode'] <= 1008) {
                        WXTTUtils.gridAdLoaded = false;
                    }
                });
                WXTTUtils.gridAd = gridAd;

            }
        }


    }
    static showGridAd() {
        if (WXTTUtils.gridAd) {
            WXTTUtils.gridAd.show().catch((err) => {
                console.error('格子广告显示错误', err)
            })
        }
    }
    static destroyGrid(): void {
        if (WXTTUtils.gridAd != null) {
            WXTTUtils.gridAd.destroy()
            WXTTUtils.gridAd = null;
        }
    }
    static videoCall: Function = null
    static showVideo(call: Function): void {
        if (DEV || sys.isBrowser) {
            call(0)
            return
        }
        // if (sys.isBrowser) 
        // {
        //     call(1)
        //     return
        // }
        WXTTUtils.videoCall = call
        WXTTUtils.videoAd.show()
            .catch(() => {
                WXTTUtils.videoAd.load()
                    .then(() => WXTTUtils.videoAd.show())
                    .catch(err => {
                        console.log('激励视频 广告显示失败', err)
                        WXTTUtils.showTip('暂无视频可用！')
                        call(-2)

                    })
            })
    }
    //加载不了，和播放视频都返回-2，切换成分享 -1是中途关闭 0=正常
    static initVideo(): void {

        if (sys.platform == sys.Platform.WECHAT_GAME) {
            if (WXTTUtils.videoAd != null) {
                return;
            }

            let videoAd = wx.createRewardedVideoAd({ adUnitId: WXTTUtils.VIDEO_ID })
            WXTTUtils.videoAd = videoAd

            videoAd.onLoad(() => {
                console.log('激励视频 广告加载成功')
            })

            videoAd.onError(err => {
                console.log(err)
                WXTTUtils.videoCall && WXTTUtils.videoCall(-2)
            })

            videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {

                    WXTTUtils.videoCall && WXTTUtils.videoCall(0)
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    WXTTUtils.videoCall && WXTTUtils.videoCall(-1)
                }

            });
        }
    }
    static vibrateShort() {
        if (wx)
            wx.vibrateShort()
    }
    // update (dt) {}
}
